<template>
	<view>
		<view class="img">
			<view class="logins">
				<view class="iconfont icon-zuo icon"></view>
				登录
			</view>
			<view class="center">
				<view class="content">
					<view class="code">
						<view class="codeSon">{{isShow?'验证码登录':'密码登录'}}</view>
						<view class="pass" @click="isShow=!isShow">{{!isShow?'验证码登录':'密码登录'}}</view>
					</view>
					<view class="ipt" v-show='isShow'>
						<view class="ipt_name">
							<input type="text" v-model="form.mobile" placeholder="请输入手机号"/>
						</view>
						<view class="ipt_pwd">
							<input type="text" v-model="form.code" placeholder="请输入验证码"/>
							<view class="auth" v-show='!isCode' @click="send">获取验证码</view>
							<view class="auth" v-show="isCode">{{time}} s</view>
						</view>
					</view>
					<view class="ipt" v-show='!isShow'>
						<view class="ipt_name">
							<input type="text" v-model="form.mobile" placeholder="请输入手机号"/>
						</view>
						<view class="ipt_pwd">
							<input type="password" v-model="form.pass" placeholder="请输入密码"/>
						</view>
					</view>
				</view>
			</view>
			<view class="login" @click="login">登录</view>
			<view class="register" @tap="$common.go('/pages/register/register')">没有账号，立即注册</view>
			<view class="box"></view>
		</view>
	</view>
</template>

<script>
	import Api from '@/api/index.js'
	import {regMobie,regCode} from '@/utils/verfy.js'
	export default {
		data() {
			return { 
				isShow : true,
				form : {
					mobile : '13522566761',
					// pass : '123456'
				},
				time : 5,
				isCode : false,
				timer : ''
			};
		},
		methods:{
			async login(){
				if(!regMobie(this.form.mobile)) return this.$message.error('请输入正确的手机号')
				let res
				if(!this.isShow){
					// 密码登录
					if(!this.form.pass) return this.$message.error('请输入正确的密码')
					res = await Api.login(this.form)
					console.log(res);
				}else{
					// 验证码登录
					if(!regCode(this.form.code)) return this.$message.error('请输入正确的验证码')
					res = await Api.loginByCode(this.form)
					console.log(res);
				}
				// 将用户信息存入缓存
				uni.setStorageSync('token',res.data.token)
				uni.setStorageSync('member',res.data.member)
				
				this.$message.success('登录成功')
			},
			async send(){
				// 验证 非空 格式
				if(!regMobie(this.form.mobile)) return this.$message.error('请输入正确的手机号')
				let res = await Api.sendCode({mobile : this.form.mobile})
				console.log(res);
				this.$message.success('发送成功')
				// 开始定时器发送
				this.isCode = true
				this.timer = setInterval(()=>{
					this.time --
					if(this.time <= 0){
						this.isCode = false
						this.time = 5
						// 清楚定时器
						clearInterval(this.timer)
					}
				},1000)
			},
		},
		beforeDestroy(){
			// 清楚定时器 防止内存泄漏
			clearInterval(this.timer)
		}
	}
</script>

<style lang="less">
@import url('login.less');
</style>